package com.fine.hair.applet.aop;

import com.fine.hair.comm.redis.RedisService;
import com.fine.hair.comm.utils.BaseException;
import com.fine.hair.comm.utils.MyStatus;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.MessageFormat;

/**
 * @author junelee
 * @date 2020/5/28 14:19
 */
@Slf4j
@Component
@Aspect
public class UserApiAround {

    /**
     * 0, uid; 1, appType
     */
    private static final String KEY_USER_TOKEN = "user:token:{0}:{1}";

    private final RedisService redisService;

    public UserApiAround(RedisService redisService) {
        this.redisService = redisService;
    }

    @Around("@annotation(com.fine.hair.applet.aop.UserApi)")
    public Object userApiAround(ProceedingJoinPoint point) throws Throwable {
        return adminApiAroundX(point);
    }

    private Object adminApiAroundX(ProceedingJoinPoint point) throws Throwable {
        log.info("API拦截切入点 {}", point);
        Method method = ((MethodSignature) point.getSignature()).getMethod();

        // 可在注解后跟 true 或 false 来决定是否执行某些代码
        UserApi api = method.getAnnotation(UserApi.class);
        if (api.login()) {
            // TODO if true do something
        }

        Object[] args = point.getArgs();
        HttpServletRequest request = (HttpServletRequest) args[0];

        String token = request.getHeader("token");
        log.debug("token = {}", token);
        String key = MessageFormat.format(KEY_USER_TOKEN, token, 1);
        String string = redisService.selectValue(key);
        if (string == null) {
            throw new BaseException(MyStatus.TOKEN_EXPIRED);
        }

        return point.proceed(point.getArgs());
    }

}
